package com.hyc.gchatsystem.file;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @projectName: gchatsystem
 * @package: com.hyc.gchatsystem.file
 * @className: FileServer
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/4/13 17:17
 * @version: 1.0
 */
//文件服务Demo
//通过 HTTP 请求 返回访问指定目录的文件列表
public class FileServer {


    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        //连接指引对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //链式编程
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设定编解码器 Netty提供的http 编解码器
                        pipeline.addLast(new HttpServerCodec());
                        //数据聚合器 因为是分段传输 处理Http消息的聚合器
                        pipeline.addLast(new HttpObjectAggregator(512 * 1024));
                        //支持大数据的文件传输 控制对内存的使用
                        pipeline.addLast(new ChunkedWriteHandler());
                        // 添加自定义处理器
                        pipeline.addLast(new FileServerHandler());
                    }
                });
        // 启动服务器
        try {
            ChannelFuture future = serverBootstrap.bind(9090).sync();
            // 阻塞关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
